package adapter.company;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;
import define.API;
import model.AllCompanyFeedItem;
import model.company.CompanyFeedItem;
import ui.activity.company.PreviewAllCompanyFeed;
import ui.activity.group_management.GroupFeed;
import ui.activity.login.Login;
import ui.fragment.company.CompanyFeedFragment;
import ui.fragment.group_management.GroupFeedFragment;


/**
 * Created by trek2000 on 21/8/2014.
 */
public class AllCompanyFeedAdapter extends BaseAdapter {

    /**
     * Data section
     */
    private ArrayList <CompanyFeedItem> mAlAllCompanyFeed = new ArrayList<>();

    /**
     * Interface section
     */

    /**
     * String section
     */
    private int textViewResourceId;
    /**
     * The other section
     */
    private Context mContext;
    private DisplayImageOptions mDio;
    private ViewHolder viewHolder;
    private GridViewAllCompanyFeedAdapter gridViewAllCompanyFeedAdapter = null;

    private class ViewHolder {
        private CircleImageView circleIvAvatar;
        private GridView mGv;
        private Button mBtnCompanyName;
        private TextView mTvElapsedTime;
        private TextView mTvFileNumberUploaded;
        private TextView mTvGroupName;
        private TextView mTvUserName;
    }

    /**
     * @param context
     */
    public AllCompanyFeedAdapter(Context context, int textViewResourceId, ArrayList <CompanyFeedItem> mAlallCompanyFeed ) {
        this.mContext = context;
        this.textViewResourceId = textViewResourceId;
        this.mAlAllCompanyFeed = mAlallCompanyFeed;

        mDio = new DisplayImageOptions.Builder()
                .delayBeforeLoading(1000)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    /**
     * @return
     */
    public int getCount() {
        return mAlAllCompanyFeed.size();
    }

    /**
     * @param position
     * @return
     */
    public CompanyFeedItem getItem(int position) {
        return mAlAllCompanyFeed.get(position);
    }

    /**
     * @param position
     * @return
     */
    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final int pos, View convertView, ViewGroup parent) {

        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(textViewResourceId, null);
            viewHolder.circleIvAvatar = (CircleImageView) convertView.findViewById(R.id.circleiv_avatar_in_simple_list_item_all_company_feed);
            viewHolder.mGv= (GridView) convertView.findViewById(R.id.gv_in_simple_list_item_all_company_feed);
            viewHolder.mBtnCompanyName = (Button) convertView.findViewById(R.id.btn_company_name_in_simple_list_item_all_company_feed);
            viewHolder.mTvElapsedTime = (TextView) convertView.findViewById(R.id.tv_elapsed_time_in_simple_list_item_all_company_feed);
            viewHolder.mTvFileNumberUploaded = (TextView) convertView.findViewById(R.id.tv_file_number_uploaded_in_simple_list_item_all_company_feed);
            viewHolder.mTvGroupName = (TextView) convertView.findViewById(R.id.tv_group_name_in_simple_list_item_all_company_feed);
            viewHolder.mTvUserName = (TextView) convertView.findViewById(R.id.tv_user_name_in_simple_list_item_all_company_feed);

            viewHolder.circleIvAvatar.setTag(pos);
            viewHolder.mGv.setTag(pos);
            viewHolder.mBtnCompanyName.setTag(pos);
            viewHolder.mTvElapsedTime.setTag(pos);
            viewHolder.mTvFileNumberUploaded.setTag(pos);
            viewHolder.mTvGroupName.setTag(pos);
            viewHolder.mTvUserName.setTag(pos);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)convertView.getTag();

            viewHolder.circleIvAvatar.setTag(pos);
            viewHolder.mGv.setTag(pos);
            viewHolder.mBtnCompanyName.setTag(pos);
            viewHolder.mTvElapsedTime.setTag(pos);
            viewHolder.mTvFileNumberUploaded.setTag(pos);
            viewHolder.mTvGroupName.setTag(pos);
            viewHolder.mTvUserName.setTag(pos);
        }
        //set data
        try {
            String URL = "";
            if (API.IS_DEV_SITE)
                URL = mAlAllCompanyFeed.get(pos).getUserAvatar().replace("https", "http");
            else
                URL = mAlAllCompanyFeed.get(pos).getUserAvatar();

            Enterprise.imageLoader.displayImage(
                    URL,
                    viewHolder.circleIvAvatar, mDio,
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                        }

                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        }

                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            if (loadedImage != null & view.findViewWithTag(pos) != null) {
                                ((ImageView) view.findViewWithTag(pos)).setImageBitmap(loadedImage);
                            }
                        }
                    }, new ImageLoadingProgressListener() {
                        @Override
                        public void onProgressUpdate(
                                String imageUri, View view, int current, int total) {
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

        ((TextView)viewHolder.mTvUserName.findViewWithTag(pos)).setText(
                mAlAllCompanyFeed.get(pos).getUserName());
        ((Button)viewHolder.mBtnCompanyName.findViewWithTag(pos)).setText(
                mAlAllCompanyFeed.get(pos).getCompanyName());
        ((TextView)viewHolder.mTvFileNumberUploaded.findViewWithTag(pos)).setText(
                "uploaded " + String.valueOf(mAlAllCompanyFeed.get(pos).getNumberOfShots()) + " items to");
        ((TextView)viewHolder.mTvGroupName.findViewWithTag(pos)).setText(
                mAlAllCompanyFeed.get(pos).getGroupName());
        viewHolder.mTvElapsedTime.setText(
                mAlAllCompanyFeed.get(pos).getElapsedTime() + " ago");

        gridViewAllCompanyFeedAdapter = new GridViewAllCompanyFeedAdapter(mContext, mAlAllCompanyFeed.get(pos).getmAlShotOfCompanyFeedItem());
        viewHolder.mGv.setAdapter(gridViewAllCompanyFeedAdapter);
        //on click listener
        viewHolder.mBtnCompanyName.findViewWithTag(pos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // go to company feed fragment
                ((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(
                        R.id.fl_in_activity_enterprise, CompanyFeedFragment.newInstance()
                ).commitAllowingStateLoss();
                Enterprise.mTvTitle.setText(mAlAllCompanyFeed.get(pos).getCompanyName());
                Enterprise.mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
                Enterprise.mIvArrowInActionBar.setVisibility(View.VISIBLE);
                /**
                 * compare company id of company selected and company id of login user info
                 * to get company id, company id group, user company id
                 * because one user join manny company with many user company id others
                 */
                for (int i = 0 ; i < Login.user.getUserInfo().getmAlCompaniesOfUserInfo().size(); i++) {
                    if (Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i).getCompanyId() ==
                            mAlAllCompanyFeed.get(pos).getCompanyId()) {
                        Enterprise.company.setCompaniesOfUserInfoSelected(Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i));
                    }
                }
                //save company name to single ton to use for api invite user to company
                Enterprise.company.setCompanyNameSelected(
                        mAlAllCompanyFeed.get(pos).getCompanyName()
                );
            }
        });
        viewHolder.mTvGroupName.findViewWithTag(pos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mContext.startActivity(new Intent(mContext, GroupFeed.class));
                /**
                 * compare company id of company selected and company id of login user info
                 * to get company id, company id group, user company id
                 * because one user join manny company with many user company id others
                 */
                for (int i = 0 ; i < Login.user.getUserInfo().getmAlCompaniesOfUserInfo().size(); i++) {
                    if (Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i).getCompanyId() ==
                            mAlAllCompanyFeed.get(pos).getCompanyId()) {
                        Enterprise.company.setCompaniesOfUserInfoSelected(Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i));
                    }
                }
                //save group id, group name to single ton, can use one object replace 2 function
                Enterprise.groupManagement.setGroupIdSelected(
                        mAlAllCompanyFeed.get(pos).getGroupId()
                );
                Log.i("","mAlAllCompanyFeed.get(pos).getGroupName() " + mAlAllCompanyFeed.get(pos).getGroupName());
                Enterprise.groupManagement.setGroupNameSelected(
                        mAlAllCompanyFeed.get(pos).getGroupName());
            }
        });
        // on item click listener
        ((GridView) viewHolder.mGv.findViewWithTag(pos)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos_of_gv, long l) {
                //save pos and pos_of_gv to company singleton
                Enterprise.company.setPositionOfAllCompanyFeedItem(pos);
                Enterprise.company.setPositionOfGridViewOfAllCompanyFeedItem(pos_of_gv);
                mContext.startActivity(new Intent(mContext, PreviewAllCompanyFeed.class));
            }
        });
        return convertView;
    }

}